package com.davidhigenbottam.HeatMap.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;

public class LoginDialog extends DialogBox {
	protected Label label= new Label("Please login.");
	protected TextBox userName = new TextBox();
	protected PasswordTextBox password = new PasswordTextBox();

	protected Button login = new Button("Login");
	protected HTML status;
	private HeatMap heatmap; 

	public LoginDialog(HeatMap heatmap) {
		super();
		
		this.heatmap= heatmap;
		this.setGlassEnabled(true);
		
		this.hide();

		FlexTable layout = new FlexTable();

		this.add(layout);

		layout.setWidget(0, 0, label);
		layout.getFlexCellFormatter().setColSpan(0, 0, 2);

		layout.setWidget(1, 0, new Label("email:"));
		layout.setWidget(1, 1, userName);
		layout.setWidget(2, 0, new Label("password:"));
		layout.setWidget(2, 1, password);

		layout.setWidget(3, 0, login);
		layout.getFlexCellFormatter().setColSpan(3, 0, 2);

		userName.setFocus(true);
		
		KeyPressHandler enterPressedHandler = new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent event) {
				char keyCode = event.getCharCode();
				if (keyCode == KeyCodes.KEY_ENTER) {
					login();
				}
			}
		};
		
		userName.addKeyPressHandler(enterPressedHandler);
		password.addKeyPressHandler(enterPressedHandler);


		login.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				login();
			}
		});
		
		this.center();
	}
	
	public void showLoginDialog(){
		userName.setFocus(true);
		this.show();
	}
	
	private void login(){
		
		String username= userName.getText();
		String pwd= password.getText();
		HeatMap.heatmapService.authenticate(username, pwd,new AsyncCallback<Boolean>() {
			@Override
			public void onSuccess(Boolean loggedIn) {
				if(loggedIn){
					LoginDialog.this.hide();
					LoginDialog.this.heatmap.loadApp();
				}
				else{
					LoginDialog.this.password.setValue("");
					LoginDialog.this.label.setText("Login failed. Please try again.");
				}
		    }
		    

			@Override
			public void onFailure(Throwable caught) {
				 HeatMap.error("heatmapService.authenticate",caught);
			}
		    
		});
	}


	
}
